<!--
 * @Description: upload-img
 * @Version: 0.0.1
 * @use: import Upload from '@/components/Upload'
 * components: { Upload },
 * <Upload></Upload>
 -->

<template>
  <div class="upload-img">
    <el-upload ref="upload" accept="image/*" name="file" list-type="picture-card" :auto-upload="autoUpload" :multiple="multiple"
               :limit="limit" :on-exceed="handleExceed" :before-upload="beforeUpload" :action="host" :data="ossData"
               :on-remove="handleRemove" :on-success="handleSucsess" :on-preview="handlePreview" :on-error="handleErrors">
      <!-- :http-request="httpRequest" -->
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { GetPictureUploadSignData } from '@/api/common'
export default {
  name: 'UploadImage',
  data () {
    return {
      host: '',
      ossData: {},
      fileList: [],
      autoUpload: true,
      dialogImageUrl: '',
      dialogVisible: false,
      // 上一张上传的图片原名称
      prevImgFileName: '',
      vistUrl: '' // 图片上传后前置域名
    }
  },
  props: {
    multiple: {
      type: Boolean,
      default: () => true
    },
    limit: {
      type: Number,
      default: NaN
    }
  },
  created () { },
  mounted () { },
  methods: {
    beforeUpload (file) {
      return new Promise((resolve, reject) => {
        GetPictureUploadSignData().then(res => {
          const data = res.data
          this.host = data.host
          let fileName = file.name
          let suffix = fileName.split('.')[1]
          const moment = new Date().getTime()
          fileName = `${moment}.${suffix}`
          this.ossData = {
            'key': `${data.dir}/${fileName}`,
            'policy': data.policy,
            'OSSAccessKeyId': data.accessKeyId,
            'signature': data.signature
          }
          // 图片上传后前置域名
          this.vistUrl = data.vistUrl
          resolve(true)
        }).catch(() => {
          this.host = ''
          this.ossData = {}
          reject(new Error(false))
        })
      })
    },

    handleSucsess (response, file, fileList) {
      const httpImgUrl = this.vistUrl + this.ossData.key
      this.fileList.push({
        uid: file.uid,
        url: httpImgUrl
      })
      this.upEmit()
    },

    handleErrors (errors, file, fileList) {
      this.upEmit()
    },

    handleRemove (file, fileList) {
      this.fileList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.fileList.splice(index, 1)
        }
      })
    },

    handleExceed (value) {
      this.$message.warning(`上传图片不可超过${this.limit}张!`)
    },
    handlePreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    upEmit () {
      let imgLists = ''
      if (this.fileList && this.fileList.length >= 1) {
        this.fileList.forEach(item => {
          imgLists += item.url + ','
        })
      }
      imgLists = imgLists.substring(imgLists.length - 1, 0)
      this.$emit('input', imgLists || '')
    }

  }
}
</script>
